// todo ======================== 点击去注册 ========================
qs('.login a').addEventListener('click', function () {
  qs('.login').style.display = 'none'
  qs('.register').style.display = 'block'
})
// todo ======================== 点击去登录 ========================
qs('.register a').addEventListener('click', function () {
  qs('.login').style.display = 'block'
  qs('.register').style.display = 'none'
})

// todo ======================== 注册功能 ========================
qs('.register form').addEventListener('submit', function (e) {
  e.preventDefault()
  const username = qs('.register [name=username]').value.trim()
  const password = qs('.register [name=password]').value.trim()
  if (username.length < 2 || username.length > 15) return alert('用户名长度2~15位')
  if (password.length < 6 || password.length > 15) return alert('密码长度6~15位')
  axios.post('/api/register', { username, password }).then(({ data: { code, message } }) => {
    // console.log(res)
    if (code !== 0) return alert(message)
    //  模拟点击 去登录
    qs('.register a').click()
  })
})
// todo ======================== 登录功能 ========================
qs('.login form').addEventListener('submit', function (e) {
  e.preventDefault()
  const username = qs('.login [name=username]').value.trim()
  const password = qs('.login [name=password]').value.trim()
  if (username.length < 2 || username.length > 15) return alert('用户名长度2~15位')
  if (password.length < 6 || password.length > 15) return alert('密码长度6~15位')
  axios.post('/api/login', { username, password }).then(({ data: { code, message, token } }) => {
    // console.log(res)
    if (code !== 0) return alert(message)
    // 把token 储存到本地
    localStorage.setItem('token', token)
    //  跳转到首页
    location.href = './index.html'
    //
  })
})
